﻿Imports System.Data.SqlClient
Imports System.Text.RegularExpressions
Public Class SqlErrorInterceptor


    Private Shared EstraerDatoUnico As New Regex("(?<=\()[^ ]+(?=\))", RegexOptions.RightToLeft)


    Public Sub InterSept(succesMessage As String, action As Action)


        Try
            action()

            If (Not succesMessage Is Nothing) Then
                MsgBox(succesMessage, 64)
            End If

        Catch ex As SqlException


            FindAndShowSQLex(ex)

        Catch ex As ArgumentException
            MsgBox(ex.Message, 48)
        Catch ex As NoNullAllowedException

            MsgBox(ex.Message, 48)
        Catch ex As ApplicationException

            MsgBox(ex.Message, 48)
        End Try


    End Sub

    Public Sub InterSeptNoMessage(action As Action)


        InterSept(Nothing, action)


    End Sub

    Private Sub FindAndShowSQLex(ex As SqlException)
        If Not ex.InnerException Is Nothing Then
            FindAndShowSQLex(ex.InnerException)
        Else

            Select Case ex.Number
                Case 50000

                    Dim DatoUnico As String = EstraerDatoUnico.Match(ex.Message).Value
                    MsgBox("No puede existir un registro con el valor" + If(DatoUnico.Equals(""), " indicado", ": " + DatoUnico), 48)

                Case 0
                    MsgBox("La aplicacion no esta conectada a la base de datos", 64)
                Case 245
                    MsgBox("No se pueden borrar roles que esten actualmente asociados a un usuario", 64)
                Case Else
                    MsgBox(ex.Message, 48)
            End Select
        End If
    End Sub


End Class
